package com.tianji.learning.mq;

import com.tianji.api.dto.remark.LikedTimesDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.domain.po.InteractionReply;
import com.tianji.learning.service.IInteractionReplyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

import static com.tianji.common.constants.MqConstants.Key.QA_LIKED_TIMES_KEY;

/**
 * 监听点赞变更的消息
 *
 * @Author wangxinyi
 * @Date 2025/1/3 15:58
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class LikeTimesChangeListener {

    private final IInteractionReplyService replyService;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("qa.liked.times.queue"),
            exchange = @Exchange(value = MqConstants.Exchange.LIKE_RECORD_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = QA_LIKED_TIMES_KEY
    ))
    public void listenReplyLikedTimesChange(List<LikedTimesDTO> dtoList) {
        log.info("MQ问答点赞数量监听器收到收到消息,{}", dtoList);
        if (CollUtils.isEmpty(dtoList)) {
            log.error("MQ问答点赞数量监听器收到收到消息失败，消息为空");
            return;
        }
        //修改问答点赞数量
        List<InteractionReply> interactionReplyList = dtoList.stream().map(x -> {
            InteractionReply interactionReply = new InteractionReply();
            interactionReply.setLikedTimes(x.getLikedTimes());
            interactionReply.setId(x.getBizId());
            return interactionReply;
        }).collect(Collectors.toList());
        replyService.updateBatchById(interactionReplyList);
    }
}

